const Router = require('koa-router')

const router = new Router()
const BASE_URL = `/api/v1/movies`

router.get(BASE_URL, async ctx => {
    const movies = MOVIES
    ctx.body = {
        status: 'success',
        data: movies
    }
})

router.get(`${BASE_URL}/:id`, async ctx => {
    const id = ctx.params.id
    const movie = MOVIES.filter(m => {
        return m.id === parseInt(id)
    })
    if (movie.length > 0) {
        ctx.body = {
            status: 'success',
            data: movie
        }
    } else {
        ctx.status = 404
        ctx.body = {
            status: 'success',
            message: `That movie does not exist: "${id}"`
        }
    }
})

router.post(`${BASE_URL}`, async ctx => {
    const movie = ctx.request.body
    const exists = !!MOVIES.find(m => {
        return m.id === parseInt(movie.id)
    })
    if (!exists) {
        MOVIES.push(movie)
        ctx.status = 201
        ctx.body = {
            status: 'success',
            data: movie
        }
    } else {
        ctx.status = 400
        ctx.body = {
            status: 'error',
            message: 'Something went wrong.'
        }
    }
})

router.put(`${BASE_URL}/:id`, async ctx => {
    const id = ctx.params.id
    const old = MOVIES.find(m => {
        return m.id === parseInt(old.id)
    })
    const movie = ctx.request.body

})

module.exports = router

const MOVIES = [{
    id: 1,
    name: '1'
}, {
    id: 2,
    name: '2'
}, {
    id: 3,
    name: '3'
}]
